<?php
class CController
{
	/**
	 * @var string id of the controller
	 */
	public $id;
	/**
	 * @var string id of the current action
	 */
	public $action;
	/**
	 * @var string name of layout that is used to display controller output
	 * layout must be placed under "APP_PATH/views/layouts" folder
	 */
	public $layout = 'main';

	/**
	 * Generates url for a virtual path
	 *
	 * @param $path
	 * @param array $params
	 * @return string
	 *
	 * Available params:
	 *
	 * $params['absolute'] if true then resulting url will be absolute
	 *
	 * Examples:
	 *
	 * C::controller()->url('user/create')
	 * C::controller()->url('contacts', array('absolute' => false))
	 */
	public function url($path, $params = array())
	{
		if (!isset($params['absolute']))
			$params['absolute'] = true;

		$basePath = '';

		if ($params['absolute'])
		{
			$basePath = C::app()->config['host'];
			if (empty($basePath))
			{
				$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']), 'https') === false ? 'http' : 'https';
				$host = $_SERVER['HTTP_HOST'];
				$basePath = $protocol.'://'.$host;
			}
		}

		$basePath = $basePath.C::app()->config['path'];

		return C::app()->config['urls']['cuteUrls'] ? $basePath.$path :
			$basePath.'?q='.$path;
	}

	/**
	 * Renders view
	 *
	 * @param $view name of the view
	 * @param array $params parameters that will be passed as a local variables to the view
	 * @return string
	 * @throws Exception
	 */
	public function render($view, $params = array())
	{
		$viewName = APP_PATH.'views/'.$view.'.php';

		if (!file_exists($viewName))
			throw new Exception('Не удается найти представление "'.$viewName.'"');

		if (is_array($params) && count($params))
		{
			foreach ($params as $_ => $__)
				$$_ = $__;
		}

		ob_start();
		include $viewName;
		return ob_get_clean();
	}

	/**
	 * Renders layout
	 *
	 * @param array $params parameters that will be passed as a local variables to the view
	 * @return string
	 * @throws Exception
	 */
	public function renderLayout($params = array())
	{
		if (empty($this->layout))
			throw new Exception('Поле CController::layout не может быть пустым');

		$layoutName = APP_PATH.'views/layouts/'.$this->layout.'.php';

		if (!file_exists($layoutName))
			throw new Exception('Не удается найти макет "'.$layoutName.'"');

		if (is_array($params) && count($params))
		{
			foreach ($params as $_ => $__)
				$$_ = $__;
		}

		ob_start();
		include $layoutName;
		return ob_get_clean();
	}
}